//
//  ProductDetailViewController.swift
//  Nahuo
//
//  Created by zang qilong on 2017/5/17.
//  Copyright © 2017年 zang qilong. All rights reserved.
//

import UIKit
import URLNavigator

final class ProductDetailViewController: UIViewController, URLNavigable {
    
    var productID:String
    let headerView = Bundle.main.loadNibNamed("ProductDetailHeader", owner: nil, options: nil)?.first as! ProductDetailHeader;
    let detailTableView = UITableView.init(frame: CGRect.zero, style: .plain)
    let fetchDetailRequest:FetchProductDetailRequest
    var product:Product?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
        fetchDetail()
        // Do any additional setup after loading the view.
    }
    
    func setupViews() {
        self.view.addSubview(detailTableView)
        detailTableView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        let width = UIScreen.main.bounds.width
        headerView.frame = CGRect(x: 0, y: 0, width: width, height: width * 1.6)
        detailTableView.tableHeaderView = headerView
        
        
    }
    
    func fetchDetail() {
        self.fetchDetailRequest.fetchProductDetail { [unowned self](product) in
            self.product = product
            self.headerView.setupHeader(model: self.product!)
            self.detailTableView.reloadData()
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: Navigator
    
    init(productID:String) {
        
        self.productID = productID
        self.fetchDetailRequest = FetchProductDetailRequest.init(id: productID)
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    convenience init?(navigation: Navigation) {
        guard let productID = navigation.values["id"] as? String else { return nil }
        self.init(productID: productID)
    }

    
}


